from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from typing import List
from datetime import timedelta
from app.schemas.user import UserCreate, UserResponse, UserUpdate, Token
from app.crud.user import get_users, get_user_by_id, create_user, update_user, delete_user, get_user_by_username
from app.auth.jwt import create_access_token
from app.auth.dependencies import get_current_active_user
from app.config import settings

router = APIRouter()

@router.post("/register", response_model=UserResponse, status_code=status.HTTP_201_CREATED)
async def register_user(user: UserCreate):
    """用户注册"""
    # 检查用户名是否已存在
    db_user = await get_user_by_username(user.username)
    if db_user:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Username already registered"
        )
    
    # 创建新用户
    new_user = await create_user(user)
    return new_user

@router.post("/login", response_model=Token)
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
    """用户登录并获取访问令牌"""
    from app.crud.user import authenticate_user
    
    user = await authenticate_user(form_data.username, form_data.password)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect username or password",
            headers={"WWW-Authenticate": "Bearer"},
        )
    
    access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": user.username}, expires_delta=access_token_expires
    )
    return {"access_token": access_token, "token_type": "bearer"}

@router.get("/users", response_model=List[UserResponse])
async def read_users(skip: int = 0, limit: int = 100, current_user: UserResponse = Depends(get_current_active_user)):
    """获取用户列表"""
    users = await get_users(skip=skip, limit=limit)
    return users

@router.get("/users/{user_id}", response_model=UserResponse)
async def read_user(user_id: str, current_user: UserResponse = Depends(get_current_active_user)):
    """根据ID获取用户"""
    user = await get_user_by_id(user_id)
    if user is None:
        raise HTTPException(status_code=404, detail="User not found")
    return user

@router.put("/users/{user_id}", response_model=UserResponse)
async def update_user_endpoint(user_id: str, user_update: UserUpdate, current_user: UserResponse = Depends(get_current_active_user)):
    """更新用户信息"""
    # 检查用户是否存在
    existing_user = await get_user_by_id(user_id)
    if existing_user is None:
        raise HTTPException(status_code=404, detail="User not found")
    
    # 更新用户
    updated_user = await update_user(user_id, user_update)
    if updated_user is None:
        raise HTTPException(status_code=400, detail="User could not be updated")
    return updated_user

@router.delete("/users/{user_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_user_endpoint(user_id: str, current_user: UserResponse = Depends(get_current_active_user)):
    """删除用户"""
    # 检查用户是否存在
    existing_user = await get_user_by_id(user_id)
    if existing_user is None:
        raise HTTPException(status_code=404, detail="User not found")
    
    # 删除用户
    success = await delete_user(user_id)
    if not success:
        raise HTTPException(status_code=400, detail="User could not be deleted")
    



@router.get("/test", status_code=status.HTTP_204_NO_CONTENT)
async def test():
    """删除用户"""
    return "hello"